import React, { useState ,useEffect , useMemo} from 'react'
import './lfr_search.css'
import { LeftOutline ,AudioOutline,AudioMutedOutline} from 'antd-mobile-icons'
import { useNavigate ,useLocation} from 'react-router-dom'
import axios from 'axios'
import { InfiniteScroll, List, DotLoading } from 'antd-mobile';

const InfiniteScrollContent = ({ hasMore }) => {
  return (<>
    {hasMore ? (<>
        <span>Loading</span>
        <DotLoading />
      </>) : (<span>--- 我是有底线的 ---</span>)}
  </>);
};

export default function Search() {
  const navigate = useNavigate()
  const [sort, setsort] = useState(['综合排序', '距离最近', '星级最高', '价格最便宜'])
  const [list,setlist] =useState([])
  const [id,setid]=useState('综合排序')
  const [name,setname]=useState('')
  const [hasMore, setHasMore] = useState(true);
  const [len,setlen]=useState(3)
  const {state}=useLocation()
 // 用于存储识别出的文本
 const [transcript, setTranscript] = useState('');
 // 存储语音识别的实例对象
 const [recognition, setRecognition] = useState(null);
 // 用于标记语音识别是否正在进行
 const [isRecording, setIsRecording] = useState(false);

 useEffect(() => {
  getlist()
     // 创建语音识别对象，处理不同浏览器的兼容性
     const speechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
     if (speechRecognition) {
         const newRecognition = new speechRecognition();
         setRecognition(newRecognition);

         // 当识别出结果时的处理函数
         newRecognition.onresult = (event) => {
             const result = event.results[0][0].transcript;
             setTranscript((prevTranscript) => prevTranscript + ' ' + result);
         };

         // 当语音识别出错时的处理函数
       

         newRecognition.onerror = (error) => {
          console.error('语音识别错误：', error);
          alert('语音识别遇到网络问题，请检查网络连接后重试。');
      };

         // 当语音识别结束时的处理函数
         newRecognition.onend = () => {
             setIsRecording(false);
         };
     }
 }, []);

 const startRecording = () => {
     if (!isRecording && recognition) {
         recognition.start();
         setIsRecording(true);
         setTranscript(''); // 每次开始新的录制，清空之前的文本
         
     }
 };

 const stopRecording = () => {
     if (isRecording && recognition) {
         recognition.stop();
         setIsRecording(false);
         setname(transcript)
     }
 };
 

  async function loadMore() {
      setTimeout(()=>{
        setlen(len+3)
        setHasMore(len<list.length);
       },3000)
  }

  const getlist=()=>{
    axios.get(`http://127.0.0.1:3000/lfr_index/hote?names=${name}`).then(res => {
      console.log(res.data);
      setlist(res.data)
    })
  }

  const newlist=useMemo(()=>{
    const list1=[...list]
     if(id=='综合排序'){
      return list1
     }else if(id=='距离最近'){
      return list1.sort((a1,b1)=>a1.pace-b1.space)
     }else if(id=='星级最高'){
      return list1.sort((a1,b1)=>a1.star-b1.star)
     }else if(id=='价格最便宜'){
      return list1.sort((a1,b1)=>a1.price-b1.price)
     }
  })

  const sou=(event)=>{
    if(event.keyCode==13){
      getlist()
      setname('')
    }
  }


  return (
    <div>
      <div className='diva1'>
        <div className='div1'>
          <p className='p' onClick={() => { navigate('/list') }}><LeftOutline /></p>
          <input className='input' value={name} onChange={(event)=>{setname(event.target.value)}} onKeyDown={(event)=>{
            sou(event)
          }}></input>
        
          {!isRecording? (
                <button  className='ss' onClick={startRecording}><AudioOutline /></button>
            ) : (
                <button className='ss'  onClick={stopRecording}><AudioMutedOutline /></button>
            )}
        </div>
      
        <div className='div2'>
        {
            sort.map((item,index) => {
              return <p className={id==item?'p':''} key={index} onClick={()=>{setid(item)}}>{item}</p>
            })
          }
        </div>
      </div>
     <div className='divb'>
     {
        newlist.slice(0,len).map(item=>{
          return <div key={item._id} className='div3' onClick={()=>{
            navigate(`/detail`,{state:{id:item._id,da:state.da,db:state.db,nights:state.nights}})
          }}>
            <img src={item.img}></img>
            <ul>
                  <li>{item.name}</li>
                  <li className='p'>{item.address}</li>
                  <li className='p1'>￥{item.price}<span className='p1'>起</span></li>
                </ul>
          </div>
        })
      }
     </div>
     <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
        <InfiniteScrollContent hasMore={hasMore}/>
      </InfiniteScroll>
    </div>
  )
}
